מבוא לתיכנות עם MATLAB 234127 Lecture 5: Boolean logic and Boolean expressions Written by Prof. Reuven Bar-Yehuda, Technion 2013 Based on slides of Dr. Eran Eden, Weizmann 2008 1
motivation Proper academic status requirements: - Average greater than 65 - Success rate greater than 2/3 We ll see new operators: - Comparison e.g. <, > - Logical e.g. &&, 2
Boolean logic What is boolean logic? Why do we need boolean logic? Any expression in Matlab is associated with a true/false value. 0 false 1 true (Actually everything besides 0 is true by default) 3
Boolean logic Examples: >> x = 4; >> y = 0; >> z = -2 * 2; Expression Value x true y false z true x + z false x * y false 4
Boolean logic You can create variables with logical values Examples: >> a = true a = 1 >> b = false b = 0 >> a + b 1 >> a * b 0 5
Relational operators What are relational operators? < (Less than) > (Greater than) <= (Less than or equal to) >= (Greater than or equal to) == (Equal to) ~= (Not equal to) Why do we need relational operators? Watch out! Common mistakes: (1)Don t confuse = and == (2)<= and NOT =< (3)>= and NOT => The purpose of the relational and logical operations is to provide true/false answers to questions that compare between objects 6
Relational operators Examples: >> x = 5; >> y = 6; 10 < x < 20 0 < 20 Expression Value x < y true x <= y true 4 > 5 false x == 5 true x ~= y true x + 1 y == 0 true 10 < x < 20 true 1 7
Boolean logic ללא שימוש בפקודת if כתבו תכנית אשר מקבלת מהמשתמש מספר דו ספרתי ומדפיסה: 1 אם ספרת האחדות קטנה מספרת העשרות, 2 אם ספרת האחדות גדולה מספרת העשרות, 3 אם ספרת האחדות שווה לספרת העשרות. למשל עבור הקלט 12 התוכנית תדפיס 2. 8
Relational operators One of the powerful things about Matlab is that relational operations also work on arrays Example >> x = 1 : 8; x = 1 2 3 4 5 6 7 8 >> y = 8 : -1 : 1; y = 8 7 6 5 4 3 2 1 >> bool_res = x > y bool_res = 0 0 0 0 1 1 1 1 9
Relational operators A bit more complicated example: x = 1 : 0.1 : 8 * pi; plot(x, sin(x)); plot(x, (sin(x) > 0).* sin(x), 'r'); 10
Logical operators What are logical operators? They provide a way to combine or negate relational expressions Logical operators Description && AND OR ~ NOT 11
Logical operators We can specify each logical operator using a truth table AND OR NOT x y x && y x y x y x ~x 0 0 0 0 0 0 0 1 0 1 0 0 1 1 1 0 1 0 0 1 0 1 1 1 1 1 1 1 12
Logical operators In a previous slide we saw that >> x = 5 >> 10 < x < 20 1 We can use logical operators to fix this. Write a statement that is true only if x is bigger than 10 AND smaller than 20. >> x = 5 >> (10 < x) && (x < 20) 0 This statement is true in matlab!#?@ 13
Logical operators More examples: >> x = 1; y = 2; z = 3; Expression Value 4 && -5 true ~0 true y > z && y > x false ~( y > z y > x ) false (1 <= x) ~((x * z / 3) < y) (((y + z) 4 * x) > 2) (y > 10) && ~(1 <= x + y) && (x^3 + y^3 > z ^2) true false 14
Operator Precedence Parentheses () Transpose (. ), power (.^), complex conjugate transpose ( ), matrix power (^) Unary plus (+), unary minus ( ), logical negation (~) Multiplication (.*), right division (./), left division(.\), matrix multiplication (*), matrix right division (/), matrix left division (\) Addition (+), subtraction ( ) Colon operator (:) Less than (<), less than or equal to (<=), greater than (>), greater than or equal to (>=), equal to (==), not equal to (~=) Element wise AND (&) Element wise OR ( ) Short circuit AND (&&) Short circuit OR ( ) 15
Controlling precedence using parentheses >> x = false; >> y = true; >> x && y true 1 >> x && (y true) 0 16
>>g = [89 91 80 98]; >>p = [3 5 5.5 4]; ביטויים לוגיים דוגמא: תקינות אקדמית ממוצע %%%%%%% >>sum(g.*p)/sum(p) 88.8000 אחוזי הצלחה %%%%%%% >>sum(p.*(g>=55))/sum(p) תקינות אקדמית %%%%%%% 1 >>sum(g.*p)/sum(p) >= 65 && sum(p.*(g>=55))/sum(p) > 2/3 1 17
Logical operators Logical operators can be easily applied to arrays: Logical operator & Description Element-wise AND Element-wise OR ~ Not Common mistakes Please notice: The difference between & and && The difference between and 18
Logical operators Example of element-wise logical operators >> x = 1 : 8; x = 1 2 3 4 5 6 7 8 >> y = 8 : -1 : 1; y = 8 7 6 5 4 3 2 1 >> bool_res = x > y bool_res = 0 0 0 0 1 1 1 1 >> (x > y) & (y <= 2) 0 0 0 0 0 0 1 1 >> (x < 2) (y < 2) 1 0 0 0 0 0 0 1 >> bool_res_neg = ~(x > y) bool_res_neg = 1 1 1 1 0 0 0 0 19
קדימויות בין אופרטורים כשלא משתמשים בסוגריים, על האופרטור. לאופרטור & יש קדימות פעולות חשבון קודמות לאופרטורים של השוואה, קודמים לאופרטורים לוגיים. דוגמא: c<0 L = a>3 & b^2<8 ככלל, מומלץ להשתמש בסוגריים כדי לקבוע את סדר ביצוע הפעולות: L = (a>3)&((b^2<8) (c<0)) ואלו 20
חישוב עצל של אופרטורים לוגיים a אם כדי לחסוך בזמן ריצה, קיימים במטלב אופרטורים לוגיים && ו-, העוצרים את החישוב ברגע שערכו אינו ניתן לשינוי. (a>3) &&((b^2<8) (c<0)) אינו גדול מ 3, ערכו של הביטוי הוא בהכרח,(false) 0 והחישוב (( b^2<8) (c<0 ))לא יתבצע. 21 הערה: חישוב עצל עלול לשנות את סדר הקדימויות הסטנדרטי: >> (a>3) && (b^2<8) (c<0 ) 0 >> (a>3) & (b^2<8) (c<0 ) 1
Operator Precedence Parentheses () Transpose (. ), power (.^), complex conjugate transpose ( ), matrix power (^) Unary plus (+), unary minus ( ), logical negation (~) Multiplication (.*), right division (./), left division(.\), matrix multiplication (*), matrix right division (/), matrix left division (\) Addition (+), subtraction ( ) Colon operator (:) Less than (<), less than or equal to (<=), greater than (>), greater than or equal to (>=), equal to (==), not equal to (~=) Element wise AND (&) Element wise OR ( ) Short circuit AND (&&) Short circuit OR ( ) 22
ביטויים לוגיים דוגמא: תקינות אקדמית >>g = [89 91 80 98]; >>p = [3 5 5.5 4]; ממוצע %%%%%%% >>sum(g.*p)/sum(p) 88.8000 אחוזי הצלחה %%%%%%% >>sum(p.*(g>=55))/sum(p) 1 תקינות אקדמית %%%%%%% >>sum(g.*p)/sum(p) >= 65 && sum(p.*(g>=55))/sum(p) > 2/3 סדר פעולות 2 1 4 3 5 13 8 7 6 10 9 12 11 23
המרה אוטומטית בין מספרים לערכים לוגיים כאשר מטלב מבצעת פעולה חשבונית או לוגית, היא ממירה באופן אוטומטי את הערכים עליהם מבוצעת הפעולה כך שיתאימו לפעולה: >> (1==1) + (2<=3) 2 >> 5 0 1 >> ( (5+1)*2) & (4-4) 0 >> (2*(2==2))^2 + 3*true + false + 7 14 24
Array indexing using logical operators Example: Get the IDs of all the employees who got a salary above 5000 and worked less than 10 days a month. >> salary = [1000, 7000, 6000, 3000, 8000]; >> work_days = [20, 8, 28, 5, 7]; >> ids = [100007, 100008, 100009, 100010, 100011]; salary > 5000 0 1 1 0 1 work_days < 10 0 1 0 1 1 (salary > 5000) & (work_days < 10) 0 1 0 0 1 >> ids((salary > 5000) & (work_days < 10)) 100008 100011 25
Sub-array searching The find operation >> x = [2 8 7 6 4 2 3]; >> find(x == 2) 1 6 >> find(x > 3) 2 3 4 5 Finds indices of all values equal to 2 Finds indices of all values bigger than 3 How do we get the values in x that are larger than 3? How do we get the value in x that is larger than 3 and is most to the right? 26
פונקצית find שימוש שכיח במשתנים לוגיים: שליפת ערכים המקיימים תנאי נתון. >> x = [2 8 7 6 4 2 3]; >> L = x > 3 L = 0 1 1 1 1 0 0 >> indices = find(l) indices = 2 3 4 5 פונקצית find מקבלת מערך לוגי L, ומחזירה מערך המכיל את האינדקסים i עבורם L(i)=true 27
פונקצית find שימוש שכיח במשתנים לוגיים: שליפת ערכים המקיימים תנאי נתון. כאשר N הוא מערך מספרים, find(n) תחזיר את האינדקסים של המספרים השונים מאפס ב N )למה?( >> N=[1-3 -4 0 0 8 9 0 8]; >> find(n) 1 2 3 6 7 9 28
פונקצית find על מערכים רב ממדיים כאשר M הוא מערך רב מימדי, find(m) תחזיר את המיקום של האברים שאינם 0 במערך הפריסה >> M=[1-3 -4; 0 0 8; 9 0 8] M = 1-3 -4 0 0 8 9 0 8 >> find(m) % use to print row rather % then column vector 1 3 4 7 8 9 29
פונקצית find על מערכים רב ממדיים אם מעוניינים לקבל את מספרי השורות והעמודות של אברים אלו, צריך להשתמש ב: >> M=[1-3 -4; 0 0 8; 9 0 8] M = 1-3 -4 0 0 8 9 0 8 >> [rows, cols]=find(m); >> rows 1 3 1 1 2 3 >> cols 1 1 2 3 3 3 30
מיעון באמצעות מערכים לוגיים על ידי שימוש במערכים לוגיים ובחוקי המיעון שלמדנו, ניתן לבחור ממערך נתון ערכים המקיימים תנאי לוגי: >> x = [2 8 7 6 4 2 3]; >> x(x>3) 8 7 6 4 שקול ל x(find(x>3)) מה יודפס על המסך אם נוסיף את הפקודות: >> b=[2-1 -3 6 0]; >> x(b<0)??? Logic array [0 1 1 1 1 0 0] Num array [2 3 4 5] 31
מיעון באמצעות מערכים לוגיים >> s='moshe'; >> t=s(s<'k') t = Mhe חוקי מיעון דומים תקפים גם למחרוזות: 32
פונקציות לוגיות מיוחדות xor([1 1 0 0], [0 1 0 1]) 1 0 0 1 עוד אופרטור לוגי: xor x y xor(x,y) 0 0 0 0 1 1 1 0 1 1 1 0 אופרטורים לוגיים על כל אברי מערך נתון: any, all all(grades>55) אוסף גדול של פרדיקטים: isprime, islogical, isempty, 33
דוגמה )ממבחן!( נתונים שני מערכי שורה a ו- b )לא ריקים(, איך ניתן לבדוק האם יש שני איברים ב- a שגדולים מכל איברי b? גדול? sum(x > b) x נתחיל משאלות יותר פשוטות: איך ניתן לבדוק מכמה איברים ב b ה סקלר איך נשווה כל איבר ב a איברים עם כל איבר ב b? נניח שב 5 b וב 4 a איברים: b1 b2 b3 b4 b5 b1 b2 b3 b4 b5 b1 b2 b3 b4 b5 b1 b2 b3 b4 b5 a1 a1 a1 a1 a1 a2 a2 a2 a2 a2 a3 a3 a3 a3 a3 a4 a4 a4 a4 a4 34
דוגמה )ממבחן!( נתונים שני מערכי שורה a ו- b )לא ריקים(, איך ניתן לבדוק האם יש שני איברים ב- a שגדולים מכל איברי b? פתרון: A = repmat(a, [length(b), 1]); B = repmat(b,[1, length(a)]); sum(sum(a > B) == length(b))==2 35